import Vue from 'vue'
import layout from './modules/layout'
import Vuex from 'vuex'
import getters from './getters'

import HelloWorld from '@/components/HelloWorld'
import Layout from '@/pages/layout'
import Login from '@/pages/login'
import { loopRoute } from '@/utils/loopRoutes.js'
import { getToken, setToken, removeToken } from '@/utils/auth.js'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: getToken(),
    user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : '' || {
      userId: 0,
      userName: '',
    },
    routes: [],
  },
  getters,
  mutations: {
    resetUser(state){
      state.token = ''
      state.user = {
        userId: 0,
        userName: '',
      }
      state.routes = []
      removeToken()
    },
    setRoutes(state, routes) {
      state.routes = routes
    },
    saveToken(state, token) {
      state.token = token
      Vue.prototype.$http.defaults.headers.Authorization = 'Bearer' + ' ' + token
      setToken(token)
    },
    saveUser(state, user) {
      //// console.log(user)
      state.user = Object.assign(state.user, user)//从user 覆盖式的复制到 state.user 并返回这个 新对象
      localStorage.setItem('user', JSON.stringify(state.user));
    }
  },
  actions: {
    async GetInfo({ commit, state }) {
      //// console.log(getToken() || '没有tokne')
      // const res = await Vue.prototype.$http.get(`/Login/menu`)// 获取权限树
      // // console.log('登录', res)
      const res = await Vue.prototype.$api.get('/module',[state.user.userName])
      let routes = []
      if(res){

         routes = loopRoute(res.msg)
       
      }

    
      // const routes = loopRoute(res.data.data.msg)
      //// console.log(routes)
      routes.unshift({
        path: '/index',
        component: Layout,
        name: "首页",
        children: [
          {
            path: '',
            name: "欢迎",
            component: () => import('@/pages/index'),
          }
        ]
      })
      routes.push({ path: '*', redirect: '/index', hidden: true })
      commit('setRoutes', routes)
      return routes
    },
  },
  modules: {
    layout,
  },
})
